package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.publish.WmNewsPublish;
import com.heima.wemedia.service.WmNewsService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.crypto.digests.SkeinEngine;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    private final WmNewsPublish wmNewsPublish;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //  Integer page = dto.getPage();
        //  Integer size = dto.getSize();
        IPage page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        //状态
        Short status = dto.getStatus();
        if (status != null) {
            lqw.eq(WmNews::getStatus, status);
        }
//所属频道id
        Integer channelId = dto.getChannelId();
        if (channelId != null) lqw.eq(WmNews::getChannelId, channelId);
//关键字
        String keyword = dto.getKeyword();
        if (!StringUtils.isBlank(keyword)) {
            lqw.like(WmNews::getTitle, keyword);
        }
        Date beginPubDate = dto.getBeginPubDate();
        Date endPubDate = dto.getEndPubDate();
        //时间范围
        //lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        if (beginPubDate != null && endPubDate != null) {
            //如果时间不为空
            lqw.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //用户
        Integer id = WmThreadLocalUtil.getUser().getId();
        lqw.eq(WmNews::getArticleId, id);
        //查询
        page = page(page, lqw);
        //封装信息
        long total = page.getTotal();
        List records = page.getRecords();
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(records);
        return responseResult;
    }

    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //判空
        if (wmNewsDto == null || wmNewsDto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //保存或修改文章

        //将信息封装到实体类
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);


        //如果有图片的话
        //将dto的图片列表集合转为,分隔的字符串，然后

        if (wmNewsDto.getImages() != null && wmNewsDto.getImages().size() > 0) {
            String imagesPath = StringUtils.join(wmNewsDto.getImages(), ",");
            wmNews.setImages(imagesPath);
        }
        //如果当前封面类型为自动,设置为null
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //调用判断保存或修改且进行执行的方法
        saveOrUpdateWmNews(wmNews);


        //如果是草稿(不需要实现保存文章和图片素材的关系逻辑),直接结束

        //不是草稿
        //获取文章内容图片 并且保存到文章和文章内容图片联合表
        String content = wmNewsDto.getContent();
        List<String> urlList = ectractUrlInfo(content);
        //联合表的插入TODO
        saveRelativeInfoForContent(urlList, wmNews.getId());


        //     保存文章封面图片和素材的关系，如果当前局面是自动，需要匹配封面图片TODO
        saveRelativeInfoForCover(wmNewsDto, wmNews, urlList);
//
        //将文章id和发布时间设置为参数TODO
        wmNewsPublish.publishWmNews(wmNews.getId(), wmNews.getPublishTime());


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, WmNews wmNews, List<String> urlList) {
    }

    private void saveRelativeInfoForContent(List<String> urlList, Integer id) {
    }

    /**
     * 提取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> res = new ArrayList<>();
        //解析json字符串
        List<Map> maps = JSON.parseArray(content, Map.class);
        //根据json示例,每个map集合有type
        //获取type为image的
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                //如果是图片
                //获取他的路径,添加到返回集合中
                String url = (String) map.get("value");
                res.add(url);
            }
        }
        return res;
    }


    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
//如果该文章没有id,说明是新增操作
        if (wmNews.getId() == null) save(wmNews);

            //如果有id是更新操作
        else {
            updateById(wmNews);
            //删除文章图片与素材的关系,
        }
    }

}
